﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using QuanLyThongTinCoSo.Common;
using QuanLyThongTinCoSo.Entity;
using QuanLyThongTinCoSo.Model;

namespace QuanLyThongTinCoSo.Biz
{
    public class UserBiz : BaseBiz
    {
        public UserBiz(Entities context)
        {
            DbContext = context;
        }

        public User Login(string username, string password)
        {
            string encodedPassword = Utilities.EncodePassword(password);

            var users = (from item in DbContext.Users
                         where (item.Username == username && item.Password == encodedPassword)
                         select item);

            if (!users.Any())
            {
                return null;
            }
            return users.First();
        }
        
        public override void Insert(BaseModel model)
        {
            DbContext.Users.Add(model as User);
            DbContext.SaveChanges();
        }

        public override void Update(BaseModel model)
        {
            DbContext.Entry(model).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

        public override void Delete(BaseModel model)
        {
            DbContext.Users.Attach(model as User);
            DbContext.Users.Remove(model as User);
            DbContext.Entry(model).State = EntityState.Deleted;

            DbContext.SaveChanges();
        }

        public override void DeleteItems(List<BaseModel> models)
        {
            foreach (User user in models)
            {
                var current = DbContext.Users.Single(u => u.Id == user.Id);

                foreach (var role in current.Roles.ToArray())
                {
                    current.Roles.Remove(role);
                }

                DbContext.Users.Attach(current);
                DbContext.Users.Remove(current);
                DbContext.Entry(current).State = EntityState.Deleted;
            }

            DbContext.SaveChanges();
        }

        public override BaseModel GetItemById(int id)
        {
            return (from item in DbContext.Users
                    where item.Id == id
                    select item).First();
        }

        public List<User> GetAll()
        {
            return DbContext.Users.ToList();
        }
    }
}
